package com.kaifamiao.tcp;
import java.io.*;
import java.net.*;

/***
 * 用循环的方式实现文件监听
 * */
public class FileClient2 {
    public final static int PORT = 12345;
    public final static String SERVER = "127.0.0.1"; // Use the server's IP address
    public final static String FOLDER_PATH = "/Users/linrui/a/";

    public static void main(String[] args) throws IOException, InterruptedException {
        while (true) {
            try (Socket socket = new Socket(SERVER, PORT)) {
                System.out.println("Connected to server!");

                DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
                sendDirectory(new File(FOLDER_PATH), dos, "");

                // Signifies end of transfer
                dos.writeBoolean(false);
                dos.writeUTF("END");

                dos.close();
                System.out.println("Transfer completed!");
            } catch (IOException e) {
                e.printStackTrace();
            }

            // Wait for 5 seconds before sending again
            Thread.sleep(5000);
        }
    }

    public static void sendDirectory(File folder, DataOutputStream dos, String path) throws IOException {
        for (File fileEntry : folder.listFiles()) {
            if (fileEntry.isDirectory()) {
                dos.writeBoolean(true);
                dos.writeUTF(path + fileEntry.getName() + "/");
                sendDirectory(fileEntry, dos, path + fileEntry.getName() + "/");
            } else {
                dos.writeBoolean(false);
                dos.writeUTF(path + fileEntry.getName());
                dos.writeLong(fileEntry.length());
                FileInputStream fis = new FileInputStream(fileEntry);
                byte[] buffer = new byte[4096];
                int read;
                while ((read = fis.read(buffer)) > 0) {
                    dos.write(buffer, 0, read);
                }
                fis.close();
            }
        }
    }
}
